package com.dsg.controller.apply;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsg.common.constants.MessageConstants;
import com.dsg.common.dto.AjaxResult;
import com.dsg.common.util.UUIDGenerator;
import com.dsg.common.util.toolbox.CollectionUtil;
import com.dsg.common.util.toolbox.DateUtil;
import com.dsg.common.util.toolbox.StringUtil;
import com.dsg.controller.base.BaseController;
import com.dsg.entity.apply.*;
import com.dsg.entity.dto.AosDtDto;
import com.dsg.entity.dto.AosHeadDto;
import com.dsg.service.apply.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 公司申請資料 前端控制器
 * </p>
 *
 * @author system
 * @since 2020-07-04
 */
@RestController
@RequestMapping("/apply/dsgApplyCom")
@Slf4j
@Api(description = "公司申請資料")
public class DsgApplyComController extends BaseController {

    @Autowired
    IDsgApplyComService service;
    @Autowired
    IDsgApplyContactService contactService;
    @Autowired
    IDsgApplyBillService billService;
    @Autowired
    IDsgApplyPayService payService;
    @Autowired
    IDsgApplyCarService carService;
    @Autowired
    IDsgApplyCardService cardService;

    @GetMapping(value = "/getAosHead")
    @ApiOperation("AOS-頭信息")
    @ApiResponses({
            @ApiResponse(response = AosHeadDto.class, code = 1, message = "ok")
    })
    public AjaxResult getAosHead(Integer appType, String appNo, String cusNo, Integer appStatus) {
        Page page = getPage();
        Page<AosHeadDto> list = service.getAosHead(page, appType, appNo, cusNo,appStatus, getEntCode());
        return json(MessageConstants.SSO_STATUS_SUCCESS, list.getRecords(), (int)list.getTotal());
    }

    @GetMapping(value = "/getAosDt")
    @ApiOperation("AOS-詳細信息")
    @ApiResponses({
            @ApiResponse(response = AosDtDto.class, code = 1, message = "ok")
    })
    public AjaxResult getAosDt(String oid) {
        List<AosDtDto> list = service.getAosDt(oid);
        return success(list);
    }

    @PutMapping(value = "/saveOrUpdate")
    @ApiOperation("新增或更新")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveOrUpdate(@RequestBody DsgApplyCom applyCom) {
        if (StringUtil.isEmpty(applyCom.getMainNo()) || StringUtil.isEmpty(applyCom.getAppNo())) {
            return fail("mainNo和appNo不能為空");
        }

        if (StringUtil.isEmpty(applyCom.getOid())) {
            applyCom.setOid(UUIDGenerator.getUUID());
            String comNo = DateUtil.format(new Date(), "yyyyMMddHHmmss");
            applyCom.setComNo(comNo);

            QueryWrapper wrapper1 = new QueryWrapper();
            wrapper1.eq("APP_NO", applyCom.getAppNo());
            DsgApplyBill bill = billService.getOne(wrapper1);
            bill.setCusId(applyCom.getOid());
            billService.updateById(bill);

//            if (DsgApplyBill.APP_TYPE_1 == bill.getAppType() || DsgApplyBill.APP_TYPE_22 == bill.getAppType()) {
                if (DsgApplyBill.APP_TYPE_1 == bill.getAppType()) {
                    LambdaUpdateWrapper<DsgApplyPay> updateWrapper = new LambdaUpdateWrapper();
                    updateWrapper.eq(DsgApplyPay::getAppNo, applyCom.getAppNo());
                    DsgApplyPay pay = new DsgApplyPay();
                    pay.setCusNo(applyCom.getComNo());
                    payService.update(pay, updateWrapper);
                }

                LambdaUpdateWrapper<DsgApplyCar> carUpdate = new LambdaUpdateWrapper<>();
                carUpdate.eq(DsgApplyCar::getAppNo, applyCom.getAppNo());
                DsgApplyCar car = new DsgApplyCar();
                car.setCusNo(applyCom.getComNo());
                carService.update(car, carUpdate);
//            }

            LambdaUpdateWrapper<DsgApplyCard> cardUpdate = new LambdaUpdateWrapper();
            cardUpdate.eq(DsgApplyCard::getAppNo, bill.getAppNo());
            DsgApplyCard card = new DsgApplyCard();
            card.setCusNo(comNo);
            cardService.update(card, cardUpdate);
        }
        service.saveOrUpdate(applyCom);
        saveContact(applyCom.getOid(), applyCom.getContactList());
        return json(MessageConstants.SSO_STATUS_SUCCESS, applyCom);
    }

    private void saveContact(String ownsId, List<DsgApplyContact> contactList) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("OID");
        wrapper.eq("PID", ownsId);
        List<DsgApplyContact> preContactList = contactService.list(wrapper);
        List<String> preOids = null;
        List<String> oids = null;
        if (CollectionUtil.isNotEmpty(preContactList)) {
            preOids = preContactList.stream().map(DsgApplyContact::getOid).collect(Collectors.toList());
        }

        if (CollectionUtil.isNotEmpty(contactList)) {
            oids = contactList.stream().map(DsgApplyContact::getOid).collect(Collectors.toList());
            for (DsgApplyContact contact:
                    contactList) {
                if (StringUtil.isEmpty(contact.getOid())) {
                    contact.setOid(UUIDGenerator.getUUID());
                    contact.setPid(ownsId);
                }
            }
            contactService.saveOrUpdateBatch(contactList);
        }

        if (CollectionUtil.isNotEmpty(preOids)) {
            if (CollectionUtil.isNotEmpty(oids)) {
                preOids.removeAll(oids);
            }
            if (CollectionUtil.isNotEmpty(preOids)) {
                contactService.removeByIds(preOids);
            }
        }
    }

    @PostMapping(value = "/add")
    @ApiOperation("新增")
    public AjaxResult add(@RequestBody DsgApplyCom applyCom) {
        applyCom.setOid(UUIDGenerator.getUUID());
        boolean falg = service.save(applyCom);
        if (falg) {
            return result(MessageConstants.SSO_STATUS_SUCCESS);
        } else {
            return result(MessageConstants.SSO_STATUS_FAIL);
        }
    }

    @PutMapping(value = "/update")
    @ApiOperation("更新")
    public AjaxResult update(@RequestBody DsgApplyCom applyCom) {
        boolean flag = service.updateById(applyCom);
        if (flag) {
            return json(MessageConstants.SSO_STATUS_SUCCESS, applyCom);
        } else {
            return result(MessageConstants.SSO_STATUS_FAIL);
        }
    }

    @DeleteMapping(value = "/delete")
    @ApiOperation("删除")
    public AjaxResult delete(String id) {
        Boolean flag = service.removeById(id);
        if (flag) {
            return result(MessageConstants.SSO_STATUS_SUCCESS);
        } else {
            return result(MessageConstants.SSO_STATUS_FAIL);
        }
    }

    @GetMapping(value = "/{mainNo}/getByBill")
    @ApiOperation("查询单条数据")
    public AjaxResult getByBill(@PathVariable String mainNo) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("MAIN_NO", mainNo);
        DsgApplyCom applyCom = service.getOne(wrapper);
        return json(MessageConstants.SSO_STATUS_SUCCESS, applyCom);
    }

    @PutMapping(value = "/edit")
    @ApiOperation("重新编辑")
    public AjaxResult check(@RequestBody DsgApplyCom applyCom) {
        applyCom.setVerify(DsgApplyCom.VERIFY_NO);
        service.updateById(applyCom);
        return json(MessageConstants.SSO_STATUS_SUCCESS, applyCom);
    }

    @PutMapping(value = "/verify")
    @ApiOperation("完成核对")
    public AjaxResult check1(@RequestBody DsgApplyCom applyCom) {
        applyCom.setVerify(DsgApplyCom.VERIFY_YES);
        service.updateById(applyCom);
        return json(MessageConstants.SSO_STATUS_SUCCESS, applyCom);
    }
}
